import pandas
import numpy
from pandas.core.frame import DataFrame
import FP_Grow_tree
def connect_string(x,ms):
	x = list(map(lambda i:sorted(i.split(ms)),x))
	l = len(x[0])
	r = []
	for i in range(len(x)):
		for j in range(i,len(x)):
			if x[i][:l-1] == x[j][:l-1] and x[i][l-1] != x[j][l-1]:
				r.append(x[i][:l-1] + sorted([x[j][l-1],x[i][l-1]]))
	return  r
def find_rule(d,support,confidence,ms=u'--'):
	result = pandas.DataFrame(index = ['support','confidence'])
	support_series = 1.0*d.sum()/len(d)
	column = list(support_series[support_series>support].index)
	k = 0
	while len(column) > 1:
		k = k + 1
		column = connect_string(column,ms)
		sf = lambda i :d[i].prod(axis=1,numeric_only=True)
		d_2 = pandas.DataFrame(list(map(sf,column)),index = [ms.join(i) for i in column]).T
		support_series_2 = 1.0*d_2[[ms.join(i) for i in column]].sum()/len(d)
		column = list(support_series_2[support_series_2>support].index)
		support_series = support_series.append(support_series_2)
		column2 = []
		for i in column:
			i = i.split(ms)
			for j in range(len(i)):
				column2.append(i[:j] + i[j+1:] + i[j:j + 1])
		cofidence_series = pandas.Series(index = [ms.join(i) for i in column2])
		for i in column2:
			cofidence_series[ms.join(i)] = support_series[ms.join(sorted(i))]/support_series[ms.join(i[:len(i) - 1])]
		for i in cofidence_series[cofidence_series > confidence].index:
			result[i] = 0.0
			result[i]['confidence'] = cofidence_series[i]
			result[i]['support'] = support_series[ms.join(sorted(i.split(ms)))]
	result = result.T
	result = pandas.DataFrame.sort_values(result,by=['confidence','support'],ascending=False)
	print(result)
path="C:/Users/admin/Desktop/w9/超市数据集.xls"
alldata=pandas.read_excel(path,header=1,shee_tname=1)
dataF=alldata.iloc[:,1:]
a=1.0
b=0.0
for i in dataF:
    data=dataF[i]
    data[data=="T"] = i
    data[data=="F"] = None
datafin=[]
for indexs in alldata.index:
    iarray=alldata.loc[indexs].values[1:-1]
    datafin.append(iarray)
datafind=DataFrame(datafin)
change=lambda x:pandas.Series(1,index=x[pandas.notnull(x)])
mapok=map(change,datafind.as_matrix())
datafinda=pandas.DataFrame(list(mapok)).fillna(0)
surpport=0.3
cfd=0.4
find_rule(datafinda,surpport,cfd)
ff=FP_Grow_tree.FP_Grow_tree(datafin,[],surpport)
ff.printfrequent()
